<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col >
        <el-button size="mini" type="primary" @click="addCoupon">新建优惠券</el-button>
         <el-radio-group style="margin-left:20px"  v-model="value" @change="changeStatus">
          <el-radio
           v-for="item in statusOptions"
          :key="item.value"
          :label="item.value"
          >{{item.lable}}
          </el-radio>
        </el-radio-group>
      </el-col>
    </el-row>
    <el-row>
      <el-col>
        <el-table
          ref="courseTable"
          :data="couponData"
          :border="true"
          :height="690"
          :header-cell-style="{background:global.mainColor}"
          style="width: 100%"
        >
          <el-table-column prop="couponName" label="优惠券名称" width="200" align="center">
          </el-table-column>
          <el-table-column prop="couponWay" label="优惠券类型" align="center" />
          <el-table-column
            prop="couponStartTime"
            label="生效日期"
            align="center"
            />
          <el-table-column prop="couponEndTime" label="失效日期" align="center"/>
          <el-table-column prop="couponQuantity" label="剩余数量" align="center" />
          <el-table-column
          prop="isRelease"
          label="状态"
          align="center"
          >
          <template slot-scope="scope">
            {{scope.row.isRelease===1?'已发布':'未发布'}}
          </template>
          </el-table-column>
          <el-table-column prop="createTime" label="申请日期" align="center"/>
          <el-table-column label="操作" align="center" width="330px">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="warning"
                @click="handlePreview( scope.row)"
              >数据统计</el-button>
              <el-button
                v-if="scope.row.isRelease === 0"
                size="mini"
                type="success"
                @click="handlePutOn(scope.row,1)"
              >启用</el-button>
              <el-button
                v-else
                size="mini"
                type="warning"
                @click="handlePutOn(scope.row,0)"
              >禁用</el-button>
              <el-button
              :disabled="scope.row.isRelease===1"
              size="mini"
              type="primary"
              @click="handleEdit(scope.$index, scope.row)">编辑</el-button>

              <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <el-row type="flex" justify="end">
      <el-pagination
        :current-page="page"
        :page-sizes="[10, 50, 100, 200]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :background="true"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-row>
    <el-dialog
      :title="isAdd?'新增优惠券':'修改优惠券'"
      :visible.sync="couponDialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close='closeAddCoupon'
      width="700px"
    >
      <jblForm :ref-name.sync="couponFormRef" :form.sync="couponForm" :value-data.sync="couponForm.valueData">
        <template v-slot:form-couponWay>
          <el-select v-model="couponForm.valueData.couponWay" placeholder="请选择">
            <el-option label="立减券" :value="0"></el-option>
            <el-option label="满减券" :value="1"></el-option>
            <el-option label="礼品券" :value="2"></el-option>
        </el-select>
        <span style="margin-left:10px;font-size:16px">
          <el-tooltip class="item" effect="dark" placement="top">
            <div style="font-size:14px" slot="content">满减券：消费时达到相应的金额后，可以用来抵扣物品（商品）部分价格的一种券<br/>
                立减券：可以用来抵扣物品（商品）部分价格的一种券<br/>
                礼品券：可以引导用户到线下门店领取礼品的券
              </div>
            <i class="el-icon-info"/>
          </el-tooltip>
          </span>
        </template>
        <template v-slot:form-img>
            <el-upload
              action="#"
              list-type="picture-card"
              :class="{disabled:isMax}"
              :limit="1"
              :http-request="httpCoupon"
              :on-change="onChange"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :on-success="handleAvatarSuccess"
              :file-list='fileList'
              :before-upload="beforeAvatarUpload">
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="dialogImgVisible">
              <img width="100%" :src="dialogImageUrl" alt="">
            </el-dialog>
        </template>
        <template v-slot:form-courseIds>
          <span v-if="couponForm.valueData.couponUsingRange === 1 && coursonOptions.length === 0" >暂无课程，请先创建课程</span>
          <el-checkbox-group v-else v-model="couponForm.valueData.courseIds">
            <el-checkbox
            v-for="item in coursonOptions"
            :key="item.value"
            :label="item.value">
            {{item.label}}
            </el-checkbox>
          </el-checkbox-group>
        </template>
      </jblForm>
      <span slot="footer" class="dialog-footer">
        <el-button v-if="isAdd" type="primary" @click="confirmAddCoupon">确定新增</el-button>
        <el-button v-else type="primary" @click="modifyCoupon">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import jblForm from '@/components/JblForm'
import { couponList, addCoupon, listByBusiness, getCouponId, updateCoupon, updateIsRelease } from '@/api/coupon'

import { couponWayClase } from '@/utils'

export default {
  name: 'CouponList',
  components: {
    jblForm
  },
  data() {
    var validateNumber = (rule, value, callback) => {
      if (typeof value !== 'number') {
        callback(new Error('请输入数字'))
      } else if (value < 1) {
        callback(new Error('必须大于0'))
      } else {
        callback()
      }
    }
    var validateFullCut = (rule, value, callback) => {
      if (value <= this.couponForm.valueData.couponMoney) {
        callback(new Error('满xx减价格必须大于金额'))
      } else if (value < 1) {
        callback(new Error('必须大于0'))
      } else {
        callback()
      }
    }
    return {
      isAdd: true, // 是否
      dialogImgVisible: false,
      dialogImageUrl: '',
      fileList: [
        // {
        //   name: '',
        //   url: ''
        // }
      ],
      couponFormRef: {},
      // 新增优惠券dialog
      couponDialog: false,
      isMax: false, // 上传图片组件
      courseIdsShow: false, // 课程复选框
      isShow: 0,
      value: 1,
      page: 1,
      pageSize: 10,
      total: 10,
      statusOptions: [
        {
          value: 1,
          lable: '使用中'
        },
        {
          value: -1,
          lable: '过期'
        }
        // {
        //   value: -2,
        //   lable: '已删除'
        // }
        // {
        //   value: 0,
        //   lable: '立减券'
        // },
        // {
        //   value: 1,
        //   lable: '满减券'
        // },
        // {
        //   value: 2,
        //   lable: '礼品券'
        // },
        // {
        //   value: 3,
        //   lable: '平台劵'
        // },
        // {
        //   value: 4,
        //   lable: '奖池券'
        // },
        // {
        //   value: null,
        //   lable: '代金券'
        // }
      ],
      coursonOptions: [], // 课程集合
      couponData: [],
      // 新增优惠券表单
      couponFormRules: {},
      couponWayOption: [// 券类型
        {
          label: '立减券',
          value: 0
        },
        {
          label: '满减券',
          value: 1
        },
        {
          label: '礼品券',
          value: 2
        },
        {
          label: '奖金池',
          value: 4
        }
      ],
      couponUsingRangeOption: [
        {
          label: '全部课程',
          value: 0
        },
        {
          label: '部分课程',
          value: 1
        }
      ],
      nullCourse: true,
      couponForm: {
        // ref: {},
        // labelWidth: '100px',
        data: [
          {
            type: 'input',
            labelWidth: '80px',
            prop: 'couponName',
            label: '名称',
            placeholder: '请填写券名称，例如：语文课程一元优惠券',
            rules: [
              { required: true, message: '请填写券名称，例如：语文课程一元优惠券', trigger: 'blur' },
              {
                min: 1,
                max: 20,
                message: '长度在 1 到 20 个字符',
                trigger: 'blur'
              }
            ]
          },
          {
            type: 'slot',
            labelWidth: '80px',
            prop: 'couponWay',
            label: '券类型',
            placeholder: '请选择券类型',
            selectOption: () => {
              return [
                {
                  label: '立减券',
                  value: 0
                },
                {
                  label: '满减券',
                  value: 1
                },
                {
                  label: '礼品券',
                  value: 2
                }
              ]
            },
            rules: [
              { required: true, message: '请选择券类型', trigger: 'change' }
            ]
          },
          {
            type: 'inputNumber',
            show: () => {
              return this.isShow === 0
            },
            min: 1,
            step: '0.01',
            labelWidth: '80px',
            prop: 'couponMoney',
            label: '立减金额',
            placeholder: '请填写优惠券金额',
            rules: [
              { validator: validateNumber, trigger: 'change' },
              { required: true, message: '请填写优惠券金额', trigger: 'blur' }
            ]
          },
          {
            type: 'inputNumber',
            show: () => {
              return this.isShow === 1
            },
            labelWidth: '80px',
            prop: 'fullCutCouponMoney',
            label: '满xx减',
            placeholder: '请填写满减金额',
            min: 1,
            rules: [
              { required: true, validator: validateNumber, trigger: 'change' },
              { validator: validateFullCut, trigger: 'blur' }
            ]
          },
          {
            type: 'inputNumber',
            show: () => {
              return this.isShow === 1
            },
            labelWidth: '80px',
            prop: 'couponMoney',
            label: '金额',
            min: 1,
            placeholder: '请填写满减金额',
            rules: [
              { validator: validateNumber, trigger: 'change' },
              { required: true, message: '请填写优惠券金额', trigger: 'blur' }
            ]
          },
          {
            type: 'slot',
            prop: 'img',
            label: '礼品图片',
            show: () => {
              return this.isShow === 2
            },
            rules: [
              { required: true, message: '请上传图片', trigger: 'change' }
            ]
          },
          {
            type: 'inputNumber',
            labelWidth: '80px',
            prop: 'couponNumber',
            label: '数量',
            placeholder: '请填写券数量',
            rules: [
              { validator: validateNumber, trigger: 'change' },
              { required: true, message: '请填写优惠券数量', trigger: 'blur' }
            ]
          },
          {
            type: 'datedaterange',
            valueFormat: 'timestamp',
            labelWidth: '80px',
            prop: 'datee',
            label: '券有效期',
            placeholder: '请填写券类型',
            pickerOptions: () => {
              return {
                disabledDate(date) {
                  return date.getTime().valueOf() <= Date.now().valueOf() - 24 * 60 * 60 * 1000
                }
              }
            },
            rules: [
              {
                required: true,
                message: '请选择时间',
                trigger: 'blur'
              }
            ]
          },
          {
            type: 'select',
            labelWidth: '80px',
            prop: 'couponUsingRange',
            label: '选择课程',
            placeholder: '请选择课程',
            selectOption: () => {
              return [
                {
                  label: '全部课程',
                  value: 0
                },
                {
                  label: '选择课程',
                  value: 1
                }
              ]
            },
            rules: [
              { required: true, message: '请选择课程', trigger: 'blur' }
            ]
          },
          {
            type: 'slot',
            show: () => {
              return this.courseIdsShow
            },
            labelWidth: '80px',
            prop: 'courseIds',
            rules: [
              { type: 'array', required: true, message: '请选择课程', trigger: 'change' }
            ]
          }
          // {
          //   type: 'checkboxGroup',
          //   show: () => {
          //     return this.courseIdsShow
          //   },
          //   labelWidth: '80px',
          //   prop: 'courseIds',
          //   checkboxGroup: () => {
          //     return this.coursonOptions
          //   },
          //   rules: [
          //     { required: true, message: '请选择课程', trigger: 'change' }
          //   ]
          // },
          // {
          //   type: 'text',
          //   show: () => {
          //     return this.couponForm.valueData.couponUsingRange === 1 && this.coursonOptions.length === 0
          //   },
          //   labelWidth: '100px',
          //   prop: 'nullCourse'
          // }
        ],
        valueData: {
          couponName: '', // 优惠名称
          couponWay: 0, // 券类型
          couponMoney: null, // 金额
          couponNumber: null, // 数量
          // couponDate: null, // 优惠券时间
          datee: [], // 优惠券时间
          couponStartTime: null, // 优惠券开始时间
          couponEndTime: null, // 优惠券结束时间
          couponUsingRange: 0, // 使用范围
          courseIds: [], // 课程id集合
          fullCutCouponMoney: null, // 满xx减
          img: '' // 图片地址
          // courseName: '',
          // lessonTime: '',
          // lessonCount: null
        }
      }
    }
  },
  computed: {
    ...mapGetters([
      'businessId',
      'businessLat',
      'businessLng',
      'name'
    ])
  },
  watch: {
    'couponForm.valueData.couponWay'(v) {
      switch (v) {
        case 0:
          this.isShow = 0
          break
        case 1:
          this.isShow = 1
          break
        case 2:
          this.isShow = 2
          break
      }
      // this.couponForm.valueData.couponUsingRange = 0
      // this.couponForm.valueData.img = ''
    },
    // 使用范围为1时调用课程列表
    'couponForm.valueData.couponUsingRange'(v) {
      if (v === 1) {
        this.getCoruson()
        this.courseIdsShow = true
      } else {
        this.courseIdsShow = false
        this.coursonOptions = []
        this.couponForm.valueData.courseIds = []
      }
    }
  },

  filters: {},
  created() {
    this.getCouponList()
  },
  mounted() {
  },
  methods: {
    handleAvatarSuccess(res, file) {
      console.log(file, 'tup')
      this.couponForm.valueData.img = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      // const isJPG = file.type === 'image/jpeg'
      // const isLt2M = file.size / 1024 / 1024 < 2

      // if (!isJPG) {
      //   this.$message.error('上传头像图片只能是 JPG 格式!')
      // }
      // if (!isLt2M) {
      //   this.$message.error('上传头像图片大小不能超过 2MB!')
      // }
      // return isJPG && isLt2M
    },
    onChange(file, fileList) {
      this.isMax = fileList.length >= 1
    },
    httpCoupon(file, fileList) {
      const raw = {
        raw: file.file,
        name: file.file.name
      }
      this.uploadImgToOss(raw).then(response => {
        const { imgUrl } = response
        this.dialogImageUrl = imgUrl
        this.couponForm.valueData.img = imgUrl
      })
    },
    // 删除图片
    handleRemove(file, fileList) {
      this.isMax = fileList.length >= 1
      this.couponForm.valueData.img = ''
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogImgVisible = true
    },
    addCoupon() {
      this.isAdd = true
      this.couponDialog = true
      this.$nextTick(() => {
        this.couponForm.valueData = {
          couponName: '', // 优惠名称
          couponWay: 0, // 券类型
          couponMoney: null, // 金额
          couponNumber: null, // 数量
          // couponDate: null, // 优惠券时间
          datee: [], // 优惠券时间
          couponStartTime: null, // 优惠券开始时间
          couponEndTime: null, // 优惠券结束时间
          couponUsingRange: 0, // 使用范围
          courseIds: [], // 课程id集合
          fullCutCouponMoney: null, // 满xx减
          img: '' // 图片地址
          // courseName: '',
          // lessonTime: '',
          // lessonCount: null
        }
        // this.couponFormRef.resetFields()
      })
    },
    coursonFormatter(k = [], v) { // 课程复选框格式化
      const couponStartTime = v[0]
      const couponEndTime = v[1]
      const courseIds = []
      const courseNames = []
      if (k.length > 0) {
        k.forEach(i => {
          courseIds.push(`#${i.split(':')[0]}#`)
          courseNames.push(i.split(':')[1])
        })
      }
      return {
        couponStartTime,
        couponEndTime,
        courseIds: courseIds.length > 0 ? courseIds.join(',') : '',
        courseNames: courseNames.length > 0 ? courseNames.join(',') : ''
      }
    },
    closeAddCoupon() {
      this.couponFormRef.resetFields()
      this.couponForm.valueData.img = ''
      this.couponForm.valueData.courseIds = []
    },
    // 确定新建优惠券
    confirmAddCoupon() {
      if (this.couponForm.valueData.couponUsingRange === 1 && this.coursonOptions.length === 0) {
        return this.$message.error('请先创建课程')
      }
      this.couponFormRef.validate((valid) => {
        if (valid) {
          const data = Object.assign({}, this.couponForm.valueData)
          let type = null
          if (data.courseIds.length > 0) {
            const classifytype = this.coursonOptions.filter(i => {
              return data.courseIds.includes(i.value)
            })
            const typeList = classifytype.map(i => i.type)
            const numList = [...new Set(typeList)]
            const p = numList.reduce((prev, curr) => {
              return prev + curr
            })
            switch (p) {
              case 1:
                type = 1
                break
              case 2:
                type = 2
                break
              case 3:
                type = 3
                break
            }
            data.type = type
          } else {
            data.type = this.$store.getters.businessInfo.type
          }
          const obj = this.coursonFormatter(data.courseIds, data.datee)
          data.couponStartTime = obj.couponStartTime
          data.couponEndTime = obj.couponEndTime + 86399000
          data.courseIds = obj.courseIds
          data.courseNames = obj.courseNames
          delete data.datee
          addCoupon({
            ...data,
            couponQuantity: data.couponNumber,
            businessId: this.businessId,
            'businessLat': this.businessLat,
            'businessLng': this.businessLng,
            'businessName': this.name
          }).then(res => {
            if (res.code !== '200') return
            TDAPP.onEvent('新建优惠券')
            this.$message({
              type: 'success',
              message: '新增成功'
            })
            this.getCouponList()
            this.couponDialog = false
            this.couponFormRef.resetFields()
          }).finally(() => {
          })
        } else {
          return false
        }
      })
    },
    changeStatus() {
      this.getCouponList()
    },
    // 编辑
    async handleEdit(index, row) {
      TDAPP.onEvent('优惠券编辑')
      this.isAdd = false
      this.couponDialog = true
      const { data } = await getCouponId({ id: row.id })
      this.fileList = data.img ? [{ url: data.img }] : []
      this.isMax = !!data.img
      if (data.courseIds.length > 0) {
        const courseIds = data.courseIds.split(',')
        const courseNames = data.courseNames.split(',')
        data.courseIds = courseIds.map((i, index) => {
          return `${i}:${courseNames[index]}`
        })
      } else {
        data.courseIds = []
      }
      data.datee = [data.couponStartTime, data.couponEndTime]
      this.couponForm.valueData = data
    },
    // 确定修改优惠券
    modifyCoupon() {
      this.couponFormRef.validate((valid) => {
        if (valid) {
          const data = Object.assign({}, this.couponForm.valueData)
          const obj = this.coursonFormatter(data.courseIds, data.datee)
          let type = null
          if (data.courseIds.length > 0) {
            const classifytype = this.coursonOptions.filter(i => {
              return data.courseIds.includes(i.value)
            })
            const typeList = classifytype.map(i => i.type)
            const numList = [...new Set(typeList)]
            const p = numList.reduce((prev, curr) => {
              return prev + curr
            })
            switch (p) {
              case 1:
                type = 1
                break
              case 2:
                type = 2
                break
              case 3:
                type = 3
                break
            }
            data.type = type
          } else {
            data.type = this.$store.getters.businessInfo.type
          }
          data.couponStartTime = obj.couponStartTime
          data.couponEndTime = obj.couponEndTime + 86399000
          data.courseIds = obj.courseIds
          data.courseNames = obj.courseNames
          updateCoupon({
            ...data,
            couponQuantity: data.couponNumber,
            businessId: this.businessId,
            'businessLat': this.businessLat,
            'businessLng': this.businessLng,
            'businessName': this.name
          }).then(res => {
            this.$message({
              type: 'success',
              message: '修改成功'
            })
            this.getCouponList()
            this.couponDialog = false
          })
        } else {
          return false
        }
      })
    },
    // 发布 or 禁用
    async handlePutOn(row, val) {
      if (val === 1) {
        const confim = await this.$confirm('优惠券一旦发布则不可再编辑，确认发布优惠券吗?', '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
        if (!confim) return
      }

      const { code } = await updateIsRelease({
        isRelease: val,
        id: row.id
      })
      if (val === 1) {
        code === '200' && this.$message({
          message: '启用成功',
          type: 'success'
        })
      } else {
        code === '200' && this.$message({
          message: '禁用成功',
          type: 'success'
        })
      }
      this.getCouponList()
    },

    // 删除
    async handleDelete(index, row) {
      const confim = await this.$confirm('删除该优惠券, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
      if (!confim) return
      const { code } = await updateCoupon({
        id: row.id,
        status: -2
      })
      code === '200' && this.$message({
        message: '删除成功',
        type: 'success'
      })
      this.getCouponList()
    },
    // 预览
    handlePreview(row) {
      TDAPP.onEvent('优惠券数据统计')
      this.$router.push({
        path: '/marketing/coupon/couponEchart',
        query: {
          id: row.id
        }
      })
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.getCouponList()
    },
    handleCurrentChange(val) {
      this.page = val
      this.getCouponList()
      this.$nextTick(() => {
        this.$refs.courseTable.bodyWrapper.scrollTop = 0
      })
    },
    getCoruson() {
      let money = null
      if (this.isShow === 0) {
        money = this.couponForm.valueData.couponMoney
      }
      if (this.isShow === 1) {
        money = this.couponForm.valueData.fullCutCouponMoney
      }
      listByBusiness({
        businessId: this.$store.getters.businessId,
        couponWay: this.couponForm.valueData.couponWay,
        couponMoney: money
      }).then(res => {
        const data = res.data
        this.coursonOptions = data.map(i => {
          return {
            label: i.name,
            value: `${i.id}:${i.name}`,
            type: i.courseType
          }
        })
      })
    },
    // 优惠券列表
    getCouponList() {
      couponList(
        {
          currentPage: this.page,
          pageSize: this.pageSize,
          status: this.value,
          businessId: this.businessId
        }
      ).then(res => {
        const { records, total } = res.data
        // console.log(res.data, records, '优惠券列表')
        records.forEach(i => {
          i.couponEndTime = `${this.$options.filters.parseTime(i.couponEndTime, '{y}-{m}-{d} {h}:{i}:{s}')}`
          i.createTime = this.$options.filters.parseTime(i.createTime, '{y}-{m}-{d} {h}:{i}')
          i.couponStartTime = this.$options.filters.parseTime(i.couponStartTime, '{y}-{m}-{d}')
          i.couponWay = couponWayClase(i.couponWay)
          // i.isRelease = couponStatus(i.isRelease)
        })
        this.couponData = records
        this.total = total
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.el-row {
  margin-bottom: 20px;
}
.disabled /deep/.el-upload--picture-card{
    display: none
}
/deep/.el-table .cell {
  display: flex;
  justify-content: center;
}
/deep/ .el-checkbox{
  // width: 100px;
}
 .el-row{
    justify-content: center;
  }
</style>
